// pages/strategy/strategy.js
// 策略数据存储
let strategies = wx.getStorageSync('tradingStrategies') || [];

Page({
  data: {
    activeTab: 'list', // list, editor, fields
    strategies: [],
    strategyName: '',
    strategyTemplate: '',
    strategyCode: `/* 
 * 自定义策略模板
 * 可用变量:
 * - data: 包含open,high,low,close,volume等历史数据
 * - params: 自定义参数对象
 */

function customStrategy(data, params) {
    // 示例策略逻辑
    const lastClose = data.close[data.close.length - 1];
    const prevClose = data.close[data.close.length - 2];
    
    if (lastClose > prevClose) {
        return {
            signal: 'BUY',
            price: lastClose,
            comment: '价格上涨趋势'
        };
    }
    
    return null;
}`
  },

  onLoad(options) {
    this.renderStrategyList();
    
    // 如果有tab参数，则切换到对应tab
    if (options.tab) {
      this.setData({
        activeTab: options.tab
      });
    }
  },

  renderStrategyList() {
    this.setData({
      strategies: strategies
    });
  },

  onSwitchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  onStrategyNameChange(e) {
    this.setData({
      strategyName: e.detail.value
    });
  },

  onStrategyTemplateChange(e) {
    this.setData({
      strategyTemplate: e.detail.value
    });
  },

  onStrategyCodeChange(e) {
    this.setData({
      strategyCode: e.detail.value
    });
  },

  onSaveStrategy() {
    const { strategyName, strategyTemplate, strategyCode } = this.data;
    
    if (!strategyName) {
      wx.showToast({
        title: '请输入策略名称',
        icon: 'none'
      });
      return;
    }
    
    const newStrategy = {
      id: Date.now().toString(),
      name: strategyName,
      type: strategyTemplate || 'custom',
      code: strategyCode,
      active: false,
      createdAt: new Date().toISOString()
    };
    
    strategies.push(newStrategy);
    wx.setStorageSync('tradingStrategies', strategies);
    
    this.renderStrategyList();
    
    wx.showToast({
      title: '策略保存成功',
      icon: 'success'
    });
    
    // 切换到列表tab
    this.setData({
      activeTab: 'list'
    });
  },

  onValidateStrategy() {
    wx.showToast({
      title: '策略验证功能待实现',
      icon: 'none'
    });
  }
});